package com.xr.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xr.constant.MessageConstant;
import com.xr.exception.CustomException;
import com.xr.pojo.SetMeal;
import com.xr.query.QueryPageBean;
import com.xr.result.PageResult;
import com.xr.result.Result;
import com.xr.service.SetMealService;

import com.xr.utils.QiNiuUtils;
import com.xr.utils.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("setMeal")
public class SetMealController {
    //远程调用
    @Reference
    private SetMealService setMealService;

    @Autowired
    private JedisPool jedisPool;

    @PostMapping("update")
    public Result update(@RequestBody SetMeal meal,Integer [] checkgroupIds) {
        try{
            //1.更新检查组
            setMealService.update(meal, checkgroupIds);
            //2.判断图片是否有更改
            SetMeal byId = setMealService.findById(meal.getId());
            if (!StringUtils.isEmpty(meal.getId())
                    && !StringUtils.isEmpty(byId.getImg())
                    && !meal.getImg().equals(byId.getImg())){
                //2.1 有新的图片的话，旧的图片就不需要了，就要删除掉
                jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,byId.getImg(
                ));
            }
            //3.修改成功，要记录有用的图片到redis集合中
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,
                    meal.getImg());
            return new Result(true,MessageConstant.EDIT_SETMEAL_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(true,MessageConstant.EDIT_SETMEAL_FAIL);
        }
    }

    //删除
    @RequestMapping("/DelSetMeal")
    public Result DelSetMeal(Integer id) throws CustomException {
        Integer row = setMealService.DelSetMeal(id);
        return new Result(true,MessageConstant.DELETE_SETMEAL_SUCCESS,row);
    }

    //根据套餐管理id查询
    @RequestMapping("/findById")
    public Result findById(Integer id){
        SetMeal meal = setMealService.findById(id);
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("domain",QiNiuUtils.DOMAIN);
        map.put("setMeal",meal);
        return new Result(true,MessageConstant.QUERY_SETMEAL_SUCCESS,map);
    }

    //通过套餐管理id选中检查组id
    @RequestMapping("/selectSetMealByGroup")
    public Result selectSetMealByGroup(Integer id){
        System.out.println("yyyyy:"+id);
        try {
            List<Integer> integerList = setMealService.selectSetMealBYGroup(id);
            return new Result(true,MessageConstant.QUERY_SETMEALLIST_SUCCESS,integerList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(false,MessageConstant.QUERY_SETMEALLIST_SUCCESS);
    }

    //图片上传
    @PostMapping("/upload")
    public Result upload(MultipartFile imgFile){
        try {
            if(imgFile != null && ! imgFile.isEmpty()){
                //1.获取原始图片名称
                String originalFilename = imgFile.getOriginalFilename();
                //2.使用UUID生成新的文件名
                String newName =UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
                //3.使用七牛云上传图片
                QiNiuUtils.uploadViaByte(imgFile.getBytes(),newName);
                //4.返回数据给页面
                //格式为:{domain:'',imgName:''}
                Map<String,String> map = new HashMap<String,String>();
                map.put("domain",QiNiuUtils.DOMAIN);
                map.put("imgName",newName);
                //5.将上传图片名称存入Redis，基于Redis的Set集合存储
                jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,newName);
                return new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS,map);

            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);
    }

    //添加
    @RequestMapping("/addSetMealCheckGroup")
    public Result addSetMealCheckGroup(@RequestBody SetMeal setMeal , Integer [] checkgroupIds){
        try {
            //1.添加套餐基础数据以及套餐与检查组的关联数据
            setMealService.addSetMealCheckGroup(setMeal,checkgroupIds);
            //2.添加成功，要记录有用的图片到redis集合中
            Jedis jedis = jedisPool.getResource();
            jedis.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setMeal.getImg());
            jedis.close();
            return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(false,MessageConstant.ADD_SETMEAL_SUCCESS);
    }

    //条件查询加分页
    @RequestMapping("/findPage")
    public Result findPage(@RequestBody QueryPageBean queryPageBean){

        PageResult page = setMealService.findPage(queryPageBean);

        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,page);

    }

}
